<?php
declare (strict_types=1);

namespace app\common\queue\website;

use app\common\exception\LogicException;
use app\common\model\website\Visit as VisitMod;
use app\common\model\website\VisitTotal;
use Exception;
use think\facade\Cache;

class Visit
{
    public function run()
    {
        $allowRunTime = 60 * 10;
        $lastTime     = Cache::get('last_website_visit_time');

        if (time() >= $lastTime + $allowRunTime) {
            try {
                $visitDatas = $this->getVisitDatas();
                $visits     = $visitTotals = [];
                foreach ($visitDatas as $ip => $visitData) {
                    $visitData = unserialize($visitData);
                    foreach ($visitData as $data_key => $resource) {
                        // 拆分数据key
                        [$mhm_id, $visit_time, $resource_type, $user_id] = explode('.', $data_key);
                        $pv = 0;
                        foreach ($resource as $resource_id => $item) {
                            $visits[] = [
                                'mhm_id'        => $mhm_id,
                                'user_id'       => $user_id,
                                'resource_type' => $resource_type,
                                'resource_id'   => $resource_id,
                                'pv'            => $item['pv'],
                                'ip'            => $ip,
                                'visit_time'    => $visit_time,
                            ];

                            $pv += $item['pv'];
                        }

                        $visitTotals[] = [
                            'user_id'       => $user_id,
                            'mhm_id'        => $mhm_id,
                            'resource_type' => $resource_type,
                            'pv'            => $pv,
                            'ip'            => $ip,
                            'visit_time'    => $visit_time,
                        ];
                    }
                }

                $visitModel      = new VisitMod();
                $visitTotalModel = new VisitTotal();
                $visitModel->limit(200)->insertAll($visits);
                $visitTotalModel->limit(200)->insertAll($visitTotals);
                // 清理
                Cache::store('redis')->handler()->del('visit_datas');
            } catch (Exception $e) {
                throw new LogicException($e->getMessage());
            }
        }

    }

    /**
     * 获取访问数据缓存
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/15
     *
     * @return array
     */
    protected function getVisitDatas(): array
    {
        $redis = Cache::store('redis')->handler();

        $datas = $redis->hGetAll('visit_datas');

        return $datas ?: [];
    }
}
